package com.sunshine.litemusic.fragment.music;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sunshine.litemusic.callback.MyCallBack;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author sunshine
 * @date 2020/5/29
 */
public class MusicViewModel extends AndroidViewModel {

    private final static String TAG = "MusicViewModel";

    public MusicViewModel(@NonNull Application application) {
        super(application);
    }

    public void getMusicUrl(int id, final MyCallBack callBack){
        String url = "https://api.imjad.cn/cloudmusic/?type=song&id=";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url + id + "&br=128000").build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    JsonArray jsonArray = JsonParser
                            .parseString(response.body().string())
                            .getAsJsonObject()
                            .getAsJsonArray("data");
                    MusicBean.MusicInfoBean musicInfoBean = new Gson().fromJson(jsonArray.get(0), MusicBean.MusicInfoBean.class);
                    callBack.callBack(musicInfoBean, null);
                }catch (Exception e){
                    Log.e(TAG, e.toString());
                }

            }
        });
    }
}
